﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;

namespace SYJ.Common
{
    /// <summary>
    /// 生成验证码类
    /// </summary>
    public class ValidateCode
    {
        public ValidateCode()
        { }
        /// <summary>
        /// 生成的验证码存在session中
        /// </summary>
        /// <param name="context">当前上下文</param>
        /// <param name="sessionKeyName">session名称</param>
        public ValidateCode(HttpContext context, string sessionKeyName)
        {
            context.Response.Expires = -9999;
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-ctrol", "no-cache");
            int length = 2;
            int noise = 30;
            int width = 80;
            int height = 38;
            string font = "tahoma 宋体 fantasy";
            string validCode = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
            // string validCode = "CHINASESE";
            string key = sessionKeyName;
            if (0 == key.Length)
            {
                key = "C5.CaptchaImageText";
            }

            if (validCode.ToUpper() == "CHINASESE")
            {
                context.Session.Add(key, this.GetChinese(length));
            }
            else
            {
                context.Session.Add(key, this.GenerateRandomCode(validCode, length));
            }
            // Create a CAPTCHA image using the text stored in the Session object.//Century Schoolbook
            CaptchaImage ci = new CaptchaImage(context.Session[key].ToString(), width, height, font, noise);

            // Change the response headers to output a JPEG image.
            context.Response.Clear();
            context.Response.ContentType = "image/jpeg";
            // Write the image to the response stream in JPEG format.
            ci.Image.Save(context.Response.OutputStream, ImageFormat.Jpeg);

            // Dispose of the CAPTCHA image object.
            ci.Dispose();


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pwdchars">传入的字符串</param>
        /// <param name="pwdlen">长度</param>
        /// <returns>生成的随机字符串</returns>
        private string GenerateRandomCode(string pwdchars, int pwdlen)
        {
            //通过调用 Random 类的 Next() 方法
            //先获得一个大于或等于 0 而小于 pwdchars 长度的整数
            //以该数作为索引值，从可用字符串中随机取字符
            //以指定的密码长度为循环次数，依次连接取得的字符
            //最后即得到所需的随机密码串了。
            StringBuilder sb = new StringBuilder();
            int iRandNum;
            Random rnd = new Random();
            for (int i = 0; i < pwdlen; i++)
            {
                iRandNum = rnd.Next(pwdchars.Length);
                //tmpstr += pwdchars[iRandNum];
                sb.Append(pwdchars[iRandNum]);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pwdchars">传入的字符串</param>
        /// <param name="pwdlen">长度</param>
        /// <returns>生成的随机字符串</returns>
        private string GenerateRandomCode(Random rnd, string pwdchars, int pwdlen)
        {
            //通过调用 Random 类的 Next() 方法
            //先获得一个大于或等于 0 而小于 pwdchars 长度的整数
            //以该数作为索引值，从可用字符串中随机取字符
            //以指定的密码长度为循环次数，依次连接取得的字符
            //最后即得到所需的随机密码串了。
            StringBuilder sb = new StringBuilder();
            int iRandNum;
            for (int i = 0; i < pwdlen; i++)
            {
                iRandNum = rnd.Next(pwdchars.Length);
                sb.Append(pwdchars[iRandNum]);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 生成随机密码
        /// </summary>
        /// <returns></returns>
        public string GenerateRandomPassWord(Random rnd)
        {
            string number = GenerateRandomCode(rnd, "0123456789", 1);
            string word = GenerateRandomCode(rnd, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz", 1);
            string code = GenerateRandomCode(rnd, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz", 6);
            string pwd = code.Insert(rnd.Next(7), number).Insert(rnd.Next(8), word);
            return pwd;
        }
        /// <summary>
        /// 生成随机密码
        /// </summary>
        /// <returns></returns>
        public string GenerateRandomPassWord()
        {
            string number = GenerateRandomCode("0123456789", 1);
            string word = GenerateRandomCode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz", 1);
            // string chars = GenerateRandomCode("~!@#$%^&*()-_+={}[]:;,.?", 1);
            string code = GenerateRandomCode("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz", 6);
            Random rnd = new Random();
            string pwd = code.Insert(rnd.Next(7), number).Insert(rnd.Next(8), word);
            return pwd;
        }
        /// <summary>
        /// 生成随机密码
        /// </summary>
        /// <param name="pwdchars"></param>
        /// <param name="pwdlen"></param>
        /// <returns></returns>
        public string GenerateRandomPassWord(string pwdchars, int pwdlen)
        {
            //通过调用 Random 类的 Next() 方法
            //先获得一个大于或等于 0 而小于 pwdchars 长度的整数
            //以该数作为索引值，从可用字符串中随机取字符
            //以指定的密码长度为循环次数，依次连接取得的字符
            //最后即得到所需的随机密码串了。
            StringBuilder sb = new StringBuilder();


            int iRandNum = 0;
            Random rnd = new Random();

            for (int i = 0; i < pwdlen; i++)
            {
                iRandNum = rnd.Next(pwdchars.Length);

                sb.Append(pwdchars[iRandNum]);
            }



            Regex regnumber = new Regex(@"\d");

            if (!regnumber.IsMatch(sb.ToString()))//至少包括一个数字
            {

                return GenerateRandomCode(pwdchars, pwdlen);
            }
            Regex regword = new Regex(@"[a-zA-Z]");

            if (!regword.IsMatch(sb.ToString()))//至少包括一个大写或小写字母
            {
                return GenerateRandomCode(pwdchars, pwdlen);

            }
            Regex regchar = new Regex(@"((?=[\x21-\x7e]+)[^A-Za-z0-9])");//至少包括一个特殊字符

            if (!regchar.IsMatch(sb.ToString()))//至少包括一个特殊字符
            {
                return GenerateRandomCode(pwdchars, pwdlen);

            }

            return sb.ToString();
        }
        /// <summary>
        /// 生成随机码
        /// </summary>
        /// <returns>随机码</returns>
        private string GenerateRandomCode()
        {
            Random random = new Random();
            string s = "";
            for (int i = 0; i < 6; i++)
            {
                s = String.Concat(s, random.Next(10).ToString());
            }
            return s;
        }

        #region  Chineseset
        private string GetChinese(int length)
        {
            Encoding gb = Encoding.GetEncoding("gb2312");
            if (length == 0)
                length = 4;
            object[] bytes = CreateRegionCode(length);
            //调用函数产生4个随机中文汉字编码 
            string resultStr = "";
            for (int i = 0; i < length; i++)
            {
                resultStr += gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
            }
            return resultStr;

            //根据汉字编码的字节数组解码出中文汉字 
            /*
            object[] bytes=CreateRegionCode(4); 
            string str1=gb.GetString((byte[])Convert.ChangeType(bytes[0], typeof(byte[]))); 
            string str2=gb.GetString((byte[])Convert.ChangeType(bytes[1], typeof(byte[]))); 
            string str3=gb.GetString((byte[])Convert.ChangeType(bytes[2], typeof(byte[]))); 
            string str4=gb.GetString((byte[])Convert.ChangeType(bytes[3], typeof(byte[]))); 
            return str1 + str2 +str3 +str4;
            */
        }

        /* 
		此函数在汉字编码范围内随机创建含两个元素的十六进制字节数组，每个字节数组代表一个汉字，并将 
		四个字节数组存储在object数组中。 
		参数：strlength，代表需要产生的汉字个数 
		*/
        public static object[] CreateRegionCode(int strlength)
        {
            //定义一个字符串数组储存汉字编码的组成元素 
            string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

            Random rnd = new Random();

            //定义一个object数组用来 
            object[] bytes = new object[strlength];

            /*每循环一次产生一个含两个元素的十六进制字节数组，并将其放入bject数组中 
            每个汉字有四个区位码组成区位码第1位和区位码第2位作为字节数组第一个元素 
            区位码第3位和区位码第4位作为字节数组第二个元素 
            */
            for (int i = 0; i < strlength; i++)
            {
                //区位码第1位 
                int r1 = rnd.Next(11, 14);
                string str_r1 = rBase[r1].Trim();

                //区位码第2位 
                rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机数发生器的 

                //种子避免产生重复值 
                int r2;
                if (r1 == 13)
                {
                    r2 = rnd.Next(0, 7);
                }
                else
                {
                    r2 = rnd.Next(0, 16);
                }
                string str_r2 = rBase[r2].Trim();

                //区位码第3位 
                rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
                int r3 = rnd.Next(10, 16);
                string str_r3 = rBase[r3].Trim();

                //区位码第4位 
                rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
                int r4;
                if (r3 == 10)
                {
                    r4 = rnd.Next(1, 16);
                }
                else if (r3 == 15)
                {
                    r4 = rnd.Next(0, 15);
                }
                else
                {
                    r4 = rnd.Next(0, 16);
                }
                string str_r4 = rBase[r4].Trim();

                //定义两个字节变量存储产生的随机汉字区位码 
                byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
                byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
                //将两个字节变量存储在字节数组中 
                byte[] str_r = new byte[] { byte1, byte2 };

                //将产生的一个汉字的字节数组放入object数组中 
                bytes.SetValue(str_r, i);

            }

            return bytes;

        }
        #endregion
    }
}
